package com.ntschy.taizhou.threaddemo;

import java.util.concurrent.*;

/**
 * @author
 * @date
 *
 */
public class ThreadPool {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        long startTime = System.currentTimeMillis();
        //  CountDownLatch countDownLatch = new CountDownLatch(5);
        //线程池的创建方式推荐使用ThreadPoolExecutor,这也是阿里官方推荐的方式,这样可以避免线程过多导致内存占用一直增加的问题
        ExecutorService threadPool = new ThreadPoolExecutor(10, 55, 1, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());

          usePoll(threadPool);
        // nouserPoll();
       // usePoll2(threadPool);
       // usePoll3(threadPool);

        //关闭线程池
        threadPool.shutdown();
        System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms");
        System.out.println(" CountDownDemo--执行结束  ");
    }

    // 这种是有效的，利用起来了多线程，在循环中多次提交任务
    private static void usePoll(ExecutorService threadPool) throws ExecutionException, InterruptedException {
        Future<String> ressss = null;
        for (int i = 0; i < 5; i++) {
             ressss= threadPool.submit(() -> {
                System.out.println("----线程" + Thread.currentThread().getId() + "启动时间为" + System.currentTimeMillis());
                try {
                    Thread.sleep(5 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return "res------11111";
            });
        }
        // 线程池带有返回值的，会阻塞主线程。(拿到所有的结果后，才会执行以后的程序)
        //System.out.println(ressss.get());
    }

    private static void nouserPoll() throws InterruptedException {
        for (int i = 0; i < 5; i++) {
            Thread.sleep(5 * 1000);
        }
    }

    // 这种是无效的，没有利用起来多线程。(之所以看起来会快，是因为不会阻塞主线程。)
    private static void usePoll2(ExecutorService threadPool) {
        threadPool.submit(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("----线程" + Thread.currentThread().getId() + "启动时间为" + System.currentTimeMillis());
                try {
                    Thread.sleep(5 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    // 线程池带有返回值的，会阻塞主线程。
    private static void usePoll3(ExecutorService threadPool) throws ExecutionException, InterruptedException {

      Future<String> res=  threadPool.submit(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("----线程" + Thread.currentThread().getId() + "启动时间为" + System.currentTimeMillis());
                try {
                    Thread.sleep(5 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "res222--";
        });
        // 线程池带有返回值的，会阻塞主线程。
       // System.out.println(res.get());
    }

}


